<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
        <el-form-item label="项目名称" prop="projectName">
          <el-select clearable v-model="queryParams.projectName" placeholder="请选择项目名称">
            <el-option v-for="contract in projectArray" :key="contract.projectName" :label="contract.projectName"
              :value="contract.projectName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目时长" prop="shichang">
          <el-input v-model="queryParams.shichang" placeholder="请输入项目时长"
            @keyup.enter.native="handleQuery" ><div slot="append">分钟</div></el-input>
        </el-form-item>
        <el-form-item label="项目金额" prop="projectPrice">
          <el-input v-model="queryParams.projectPrice" placeholder="请输入项目金额"
            @keyup.enter.native="handleQuery"><div slot="append">元</div></el-input>
        </el-form-item>
        <el-form-item class="lastForm">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['project:fwproject:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleEdit" v-hasPermi="['project:fwproject:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="single" @click="handleDel" v-hasPermi="['project:fwproject:remove']">删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="tabList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目名称" align="center" prop="projectName" />
        <el-table-column label="项目时长(分钟)" align="center" prop="shichang" />
        <el-table-column label="项目功能" align="center" prop="projectFeature" />
        <el-table-column label="项目照片" align="center" prop="projectImgurl">
          <template slot-scope="scope">
            <div @click="lookNotes(scope.row)" style="color:cornflowerblue;cursor: pointer;">点击查看</div>
          </template>
        </el-table-column>
        <el-table-column label="项目金额(元)" align="center" prop="projectPrice" />
        <el-table-column label="销售量" align="center" prop="projectSold">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.projectSold"  @input="e => soldNumInput(e, scope.$index)" 
              @change="e => soldChange(e, scope.$index, scope.row)" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="上下架" align="center" prop="projectStatus" >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.projectStatus" active-value="1" inactive-value="0"
                  @change="val=>changeSkuswitch(val,scope.row)"></el-switch>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="项目功能" prop="projectFeature">
              <el-input v-model="form.projectFeature" placeholder="请输入项目功能" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="项目时长" prop="shichang">
              <el-input v-model="form.shichang" placeholder="请输入项目时长" type="number" ><div slot="append">min</div></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="项目金额" prop="projectPrice">
              <el-input v-model="form.projectPrice" placeholder="请输入项目金额" type="number" ><div slot="append">元</div></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="20">
            <el-form-item label="项目图片" prop="projectImgurlSmall">
              <div class="uploadImage">
                缩略图 <span>（最大允许上传个数1张）</span>
                <div>
                  <el-upload ref="upload" :action="uploadURL" :headers="headers" :data="dir" :file-list="projectImgurlSmallArray"
                    :on-success="imgSuccess" list-type="picture-card" :on-preview="handlePictureCardPreview" 
                    :on-remove="imgRemove" :before-upload="beforeUploadClick" :limit="1">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
            <el-form-item prop="projectImgurl">
              <div class="uploadImage">
               展示图 <span>（最大允许上传个数1张）</span>
                <div>
                  <el-upload ref="upload" :action="uploadURL" :headers="headers" :data="dir" :file-list="projectImgurlArray"
                    :on-success="showImgSuccess" list-type="picture-card" :on-preview="handlePictureCardPreview" 
                    :on-remove="showImgRemove" :before-upload="beforeUploadClick" :limit="1">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
            <el-form-item prop="projectDetailsImgurl">
              <div class="uploadImage">
               详情图 <span>（最大允许上传个数1张）</span>
                <div>
                  <!-- :before-remove="handleBeforeRemove" -->
                  <el-upload ref="upload" :action="uploadURL" :headers="headers" :data="dir" :file-list="projectDetailsImgurlArray"
                    :on-success="DetailsImgSuccess" list-type="picture-card" :on-preview="handlePictureCardPreview" 
                    :on-remove="DetailsImgRemove" :before-upload="beforeUploadClick" :limit="1">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
      <el-dialog :visible.sync="picShow" title="项目照片">
        <el-image style="width: 100px; height: 100px" :src="item.url"  v-for="(item,index) in srcList" :preview-src-list="[item.url]"> </el-image>
        <!-- <el-image style="width: 100px; height: 100px" :src="url"  v-for="url in srcList" :preview-src-list="srcList"> </el-image> -->
      </el-dialog>
      <el-dialog :visible.sync="dialogVisible" size="tiny">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </template>
    
  <script>
  import { fwprojectList,updateStatus,selectList,fwprojectDel,fwprojectAdd,fwprojectEdit,fwprojectDetail, editSoldNum} from "@/api/projectManage/projectManage";
  import { deleteOssFileByFileName} from "@/api/common/common";

  import { getToken } from '@/utils/auth'
  export default {
    name: "Knowledge",
    components: {
    },
    data() {
      const validateImgurlSmall = (rule, value, callback) => {
        if (!this.projectImgurlSmallArray || this.projectImgurlSmallArray.length < 1){
          callback(new Error('请上传缩略图'))
        }else{
          callback()
        }
      }
      const validateImgurl = (rule, value, callback) => {
        if (!this.projectImgurlArray || this.projectImgurlArray.length < 1){
          callback(new Error('请上传展示图'))
        }else{
          callback()
        }
      }
      const validateDetailsImgurl = (rule, value, callback) => {
        if (!this.projectImgurlArray || this.projectDetailsImgurlArray.length < 1){
          callback(new Error('请上传详情图'))
        }else{
          callback()
        }
      }
      return {
        activeName: "first",
        dialogImageUrl: '',
        dialogVisible: false,
        headers: {
          'Authorization': 'Bearer ' + getToken()
        },
        uploadURL: this.$store.state.user.uploadURL + '/oss/uploadFile2OSS',
        dir: {
          "dirData": "dcdj/image"
        },
        sfdir: {
          "dirData": "knowledgeBase/image"
        },
        replaceUrl: this.$store.state.user.replaceUrl,
        picShow:false,
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 表格数据
        tabList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        picShow:false,
        companyTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          projectName:null,
          shichang:null,
          projectPrice:null,
        },
        rules:{
          projectName:[
            { required: true, message: "项目名称不能为空", trigger: "blur" }
          ],
          shichang:[
            { required: true, message: "项目时长不能为空", trigger: "blur" }
          ],
          projectPrice:[
            { required: true, message: "项目金额不能为空", trigger: "blur" }
          ],
          projectFeature:[
            { required: true, message: "项目功能不能为空", trigger: "blur" }
          ],
          projectImgurlSmall: [
            { required: true, validator: validateImgurlSmall, trigger: "change" }
          ],
          projectImgurl: [
            { required: true, validator: validateImgurl, trigger: "change" }
          ],
          projectDetailsImgurl: [
            { required: true, validator: validateDetailsImgurl, trigger: "change" }
          ],
        },
        form:{},
        srcList:[],
        projectArray:[],
        projectImgurlSmallArray:[],//缩略图
        projectImgurlArray:[],//展示图
        projectDetailsImgurlArray:[],//详情图
      };
    },
    created() {
      this.getList();
      this.getSelectList()
      //在字典查询-区县
      this.getDicts("user_area").then(response => {
        this.userAreaArray = response.data;
      });
    },
    methods: {
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      resetAdd() {
        this.resetForm("form");
        this.form = {
          projectName: null,
          shichang: null,
          projectPrice: null,
          projectFeature: null,
        };
        this.projectImgurlSmallArray = [];
        this.projectImgurlArray = [];
        this.projectDetailsImgurlArray=[];
      },
      /** 查询产品入库列表 */
      getList() {
        this.loading = true;
        fwprojectList(this.queryParams).then(response => {
          this.tabList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getSelectList(){
        selectList().then(response => {
          this.projectArray = response.data;
        });
      },
      //查看项目照片
      lookNotes(row){
        this.srcList = []
        if (row.projectImgurl) {
            this.srcList = this.srcList.concat(JSON.parse(row.projectImgurl));
        }
        if (row.projectImgurlSmall) {
          this.srcList = this.srcList.concat(JSON.parse(row.projectImgurlSmall));
        }
        if (row.projectDetailsImgurl) {
          this.srcList = this.srcList.concat(JSON.parse(row.projectDetailsImgurl));
        }
        this.picShow = true
      },
      changeSkuswitch(val, item) {
        let text = item.projectStatus === "1" ? '继续' : '暂停' ;
        this.$modal.confirm('确认' + text + '此项目服务？').then(function() {
          return updateStatus({
              id: item.id,
              projectStatus:val,
            });
        }).then(() => {
          this.$modal.msgSuccess("操作成功");
        }).catch(function() {
          item.projectStatus = item.projectStatus === "0" ? "1" : "0";
        });
      },
      //新增
      handleAdd(){
        this.title = "新增";
        this.open = true
        this.resetAdd()
      },
      //修改
      handleEdit(row){
        this.resetAdd()
        const id = row.id || this.ids;
        fwprojectDetail(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改";
          if (response.data.projectImgurl) {
            this.projectImgurlArray = JSON.parse(response.data.projectImgurl);
          }
          if (response.data.projectImgurlSmall) {
            this.projectImgurlSmallArray = JSON.parse(response.data.projectImgurlSmall);
          }
          if (response.data.projectDetailsImgurl) {
            this.projectDetailsImgurlArray = JSON.parse(response.data.projectDetailsImgurl);
          }
        });
      },
      //删除
      handleDel(row){
        const id = row.id || this.ids;
        this.$confirm('确认删除此项目信息', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return fwprojectDel(id);
        }).then(() => {
          this.$message({message: '删除成功',type: 'success'});
          this.getList();
        })
      },
      cancel(){
        this.open = false
        this.picShow = false
      },
      submit(){
        let projectImgSmallArray = this.projectImgurlSmallArray.map(item => {
          return {url:item.url}
        });
        let projectImgArray = this.projectImgurlArray.map(item => {
          return {url:item.url}
        });
        let projectDetailsImgArray = this.projectDetailsImgurlArray.map(item => {
          return {url:item.url}
        });
        this.form.projectImgurlSmall = JSON.stringify(projectImgSmallArray);
        this.form.projectImgurl = JSON.stringify(projectImgArray);
        this.form.projectDetailsImgurl = JSON.stringify(projectDetailsImgArray);
        // this.form.projectImgurlSmall =  this.projectImgurlSmallArray.map(item => item.url).join(',');
        // this.form.projectImgurl =  this.projectImgurlArray.map(item => item.url).join(',');
        // this.form.projectDetailsImgurl =  this.projectDetailsImgurlArray.map(item => item.url).join(',');
        console.log(this.form)
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              fwprojectEdit(this.form).then(response => {
                // this.$message({ message: '修改成功', type: 'success' });
                this.open = false;
                this.getList();
              });
            } else {
              fwprojectAdd(this.form).then(response => {
                if (response.msg == "操作成功") {
                  // this.$message({ message: '新增成功', type: 'success' });
                  this.open = false;
                  this.resetAdd() 
                  this.getList();
                  this.getSelectList()
                }
              });
            }
          }
        });
      },
      //缩略图上传成功
      imgSuccess(response, file, fileList) {
        if (200 != response.code){
          this.$message.error(response.msg);
          //从文件列表删除
          // this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(file), 1)
        }else{
          let imgName = {
            cover: true,
            name: '',
            url: ''
          };
          var flieArr = file.name.split('.')
          var suffix = flieArr[flieArr.length - 1]
          var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'PNG', 'JPG', 'JPEG', 'BMP', 'GIF',]
          var result = imglist.some(function (item) {
            return item == suffix
          });
          if (result) {
            imgName.type = 1;
          }
          if (suffix == 'mp4' || suffix == 'MP4') {
            imgName.type = 2;
          }
          imgName.name = file.name;
          imgName.url = response.data;
          this.projectImgurlSmallArray.push(imgName);
        }  
      },
      imgRemove(file, fileList) {
        let oldImg = file.url;
        let newImg = oldImg.replace(this.$store.state.user.replaceUrl, '');
        deleteOssFileByFileName({
          fileName: newImg
        }).then(res => {
          this.projectImgurlSmallArray = fileList;
        });
      },
      showImgSuccess(response, file, fileList) {
        if (200 != response.code){
          this.$message.error(response.msg);
          //从文件列表删除
          // this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(file), 1)
        }else{
          let imgName = {
            cover: true,
            name: '',
            url: ''
          };
          var flieArr = file.name.split('.')
          var suffix = flieArr[flieArr.length - 1]
          var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'PNG', 'JPG', 'JPEG', 'BMP', 'GIF',]
          var result = imglist.some(function (item) {
            return item == suffix
          });
          if (result) {
            imgName.type = 1;
          }
          if (suffix == 'mp4' || suffix == 'MP4') {
            imgName.type = 2;
          }
          imgName.name = file.name;
          imgName.url = response.data;
          this.projectImgurlArray.push(imgName);
        }  
      },
      showImgRemove(file, fileList) {
        let oldImg = file.url;
        let newImg = oldImg.replace(this.$store.state.user.replaceUrl, '');
        deleteOssFileByFileName({
          fileName: newImg
        }).then(res => {
          this.projectImgurlArray = fileList;
        });
      },
      DetailsImgSuccess(response, file, fileList) {
        if (200 != response.code){
          this.$message.error(response.msg);
          //从文件列表删除
          // this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(file), 1)
        }else{
          let imgName = {
            cover: true,
            name: '',
            url: ''
          };
          var flieArr = file.name.split('.')
          var suffix = flieArr[flieArr.length - 1]
          var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'PNG', 'JPG', 'JPEG', 'BMP', 'GIF',]
          var result = imglist.some(function (item) {
            return item == suffix
          });
          if (result) {
            imgName.type = 1;
          }
          if (suffix == 'mp4' || suffix == 'MP4') {
            imgName.type = 2;
          }
          imgName.name = file.name;
          imgName.url = response.data;
          this.projectDetailsImgurlArray.push(imgName);
        }  
      },
      DetailsImgRemove(file, fileList) {
        let oldImg = file.url;
        let newImg = oldImg.replace(this.$store.state.user.replaceUrl, '');
        deleteOssFileByFileName({
          fileName: newImg
        }).then(res => {
          this.projectDetailsImgurlArray = fileList;
        });
      },
      handlePictureCardPreview(file) {
        this.dialogVisible = true;
        console.log(file.url)
        console.log(this.dialogVisible)
        this.dialogImageUrl = file.url
        
      },
      handleBeforeRemove(file, fileList){
        return this.$confirm('确定删除当前图片？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });
      },
      beforeUploadClick(file){
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      soldNumInput(e, index){
        let value = e.replace(/[^\d]/g,''); // 只能输入数字
        value = value.replace(/^0+(\d)/,"$1"); // 第一位0开头，0后面为数字
        value = value.replace(/(\d{15})\d*/,'$1') // 最多保留15位整数 
        this.tabList[index].projectSold = value
      },
      soldChange(e, index, row){
        let value = e.replace(/[^\d]/g,''); // 只能输入数字
        value = value.replace(/^0+(\d)/,"$1"); // 第一位0开头，0后面为数字
        value = value.replace(/(\d{15})\d*/,'$1') // 最多保留15位整数 
        editSoldNum({id:row.id, projectSold:row.projectSold}).then(response => {
          this.$message({message: '修改成功',type: 'success'});
          this.tabList[index].projectSold = value;
        });
      },
    }
  };
  </script>
  <style>
  .dialog-footer{
    text-align: center;
  }
  .colorRed{
    color:red
  }
  </style>
    